import React, { useEffect, useRef, useState } from "react";
import { Alert, Image, Text, TouchableOpacity, View } from "react-native";
import { MaterialIcons } from "@expo/vector-icons";
import styles from "./video-realtime-call.style";
import {SignalMessageResponse, SignalType} from "@/types/webrtc";
import { RTCView } from "react-native-webrtc";

import useDotsWaiting from "@/hooks/common/dots-waiting";
import {useWebRTCCall} from "@/hooks/webrtc/user-call";
import {useUserProfileState} from "@/hooks/user/user-profile";
import {ChatUser} from "@/types/chat-message";
import {useRoute} from "@react-navigation/native";
import {router} from "expo-router"; // 根据你项目调整路由库导入

interface VideoRealTimeCallRouteProps {
    id: string;
    name: string;
    avatar: string;
}

export default function VideoRealTimeCall() {
    const { id, name, avatar } = useRoute().params as VideoRealTimeCallRouteProps;

    const dots = useDotsWaiting({ enabled: true });

    // 假设 currentUser 信息通过其他方式获取（这里用假设）
    const {currentUser} = useUserProfileState();
    const chatUser: ChatUser = {
        avatar: currentUser.avatar,
        id: currentUser.id,
        name: currentUser.nickname,
        updateTime: currentUser.updateTime,
    }

    const {
        localStream,
        remoteStream,
        callUser,
        handleOffer,
        handleAnswer,
        handleCandidate,
        hangUp,
    } = useWebRTCCall(chatUser);

    const [signal, setSignal] = useState<SignalMessageResponse>({payload: undefined, tip: "", user: undefined, type: SignalType.NO_START });
    const [accepted, setAccepted] = useState(false);

    // 处理挂断
    const handleDisconnect = () => {
        // 发送挂断信令给对方
        hangUp();

        // 返回上一级页面
        router.back();
    };

    // 处理接听
    const handleAccept = () => {
        setAccepted(true);
        if (signal.type === SignalType.OFFER) {
            handleOffer(signal.payload, signal.user.id);
        }
    };

    // 监听信令变化（这里示例演示，实际信令应由订阅组件注入）
    // 你需要在调用此页面之前，通过状态管理把signal传入或用路由传递
    useEffect(() => {
        // 模拟接收到外部信令
        // 实际请替换为你的信令订阅后的回调传入signal
    }, []);

    // 监听远端流断开自动挂断（可选）
    useEffect(() => {
        if (accepted && !remoteStream) {
            Alert.alert("对方已挂断");
            handleDisconnect();
        }
    }, [remoteStream]);

    const renderStatusText = () => {
        switch (signal.type) {
            case SignalType.OFFER:
                return <Text style={styles.statusText}>来电中{dots}</Text>;
            case SignalType.ANSWER:
                return <Text style={styles.statusText}>通话中</Text>;
            default:
                return <Text style={styles.statusText}>等待中</Text>;
        }
    };

    const renderCallView = () => {
        if (accepted) {
            return (
                <View style={styles.videoContainer}>
                    {localStream && (
                        <RTCView streamURL={localStream.toURL()} objectFit="cover" style={styles.rtcView} />
                    )}
                    {remoteStream && (
                        <RTCView streamURL={remoteStream.toURL()} objectFit="cover" style={styles.rtcView} />
                    )}
                    <TouchableOpacity onPress={handleDisconnect} style={styles.controlButton}>
                        <MaterialIcons name="call-end" size={32} color="white" style={styles.hangupButton} />
                        <Text style={styles.controlLabel}>挂断</Text>
                    </TouchableOpacity>
                </View>
            );
        } else {
            return (
                <View style={styles.container}>
                    <Image source={{ uri: avatar }} style={styles.avatar} />
                    <Text style={styles.nameText}>{name}</Text>
                    {renderStatusText()}
                    <View style={styles.controlsRow}>
                        {signal.type === SignalType.OFFER ? (
                            <>
                                <TouchableOpacity onPress={handleAccept} style={styles.controlButton}>
                                    <MaterialIcons
                                        name="call"
                                        size={32}
                                        color="white"
                                        style={[styles.circleButton, { backgroundColor: "green" }]}
                                    />
                                    <Text style={styles.controlLabel}>接听</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={handleDisconnect} style={styles.controlButton}>
                                    <MaterialIcons
                                        name="call-end"
                                        size={32}
                                        color="white"
                                        style={styles.hangupButton}
                                    />
                                    <Text style={styles.controlLabel}>拒绝</Text>
                                </TouchableOpacity>
                            </>
                        ) : (
                            <TouchableOpacity onPress={handleDisconnect} style={styles.controlButton}>
                                <MaterialIcons
                                    name="call-end"
                                    size={32}
                                    color="white"
                                    style={styles.hangupButton}
                                />
                                <Text style={styles.controlLabel}>挂断</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                </View>
            );
        }
    };

    return renderCallView();
}
